import axios from 'axios'
import { Toast } from 'vant'
import store from '@/store'

const myAxios = axios.create({
  baseURL: 'http://smart-shop.itheima.net/index.php?s=/api',
  timeout: 5000
})

myAxios.interceptors.request.use(function (config) {
  // 加载轻提示
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
    duration: 0
  })
  config.headers.platform = 'H5' // 添加平台标识
  const token = store.getters.token // 获取token
  // 添加token
  if (token) {
    config.headers['Access-Token'] = token
  }

  return config
}, function (error) {
  return Promise.reject(error)
})

myAxios.interceptors.response.use(function (response) {
  const data = response.data
  if (data.status !== 200) {
    Toast(data.message)
    return Promise.reject(data.message)
  } else {
    // 关闭加载轻提示
    Toast.clear()

    return data
  }
}, function (error) {
  return Promise.reject(error)
})

export default myAxios
